<?php

declare(strict_types=1);

namespace App\Goods\Model;

use App\Lib\Library\Helper;
use Mine\MineModel;

/**
 * @property int $id 规格值ID
 * @property string $spec_value 规格值
 * @property int $spec_id 规格组ID
 * @property int $store_id 商城ID
 * @property int $create_time 创建时间
 * @property int $update_time 更新时间
 */
class GoodsSpecValue extends MineModel
{
    protected ?string $dateFormat = 'U';
    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'goods_spec_value';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = ['id', 'spec_value', 'spec_id', 'store_id', 'create_time', 'update_time'];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'spec_id' => 'integer', 'store_id' => 'integer', 'create_time' => 'integer', 'update_time' => 'integer'];


    private static function getListByValues(int $specId, array $values, int $storeId = null)
    {
        return self::query()->where('spec_id', '=', $specId)
            ->whereIn('spec_value', $values)
            ->where('store_id', '=', $storeId)
            ->get();
    }

    public static function getNewValueList(int $specId, array $valueList, int $storeId = null): array
    {
        // 规格组名称合集
        $values = Helper::getArrayColumn($valueList, 'spec_value');
        // 获取到已存在的规格值
        $alreadyDataDb = static::getListByValues($specId, $values, $storeId);
        $alreadyData=$alreadyDataDb->isEmpty()?[]:$alreadyDataDb->toArray();
        // 遍历整理新的规格集
        foreach ($valueList as $key => &$item) {
            $alreadyItem = Helper::getArrayItemByColumn($alreadyData, 'spec_value', $item['spec_value']);
            if (!empty($alreadyItem)) {
                // 规格值已存在的记录spec_value_id
                $item['spec_value_id'] = $alreadyItem['id'];
            } else {
                // 规格值不存在的新增记录
                $result = self::add($specId, $item, $storeId);
                $item['spec_value_id'] = $result['id'];
            }
        }
        return $valueList;
    }

    private static function add(int $specId, array $item, int $storeId = null)
    {
        return self::create([
            'spec_value' => $item['spec_value'],
            'spec_id' => $specId,
            'store_id' => !empty($storeId) ? $storeId : 0
        ]);
    }
}